<script setup lang="ts">
import { HomeWrap } from '@/components/HomeWrap'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { cartList } from '@/api/cart/client'
import type { CartWithProductInfo } from '@/api/cart/types'
import { placeOrder } from '@/api/order/client'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'Checkout'
})

const router = useRouter()

// 购物车商品列表
const cartItems = ref<CartWithProductInfo[]>([])

// 订单备注
const remark = ref('')

// 总金额
const totalMoney = ref(0)

// 计算总金额
const calculateTotal = () => {
  totalMoney.value = cartItems.value.reduce((total, item) => {
    return total + item.productSku.price * item.cart.qty
  }, 0)
}

// 获取购物车列表
const fetchCartList = async () => {
  try {
    const res = await cartList({})
    if (res && res.data && res.data.list) {
      cartItems.value = res.data.list
      calculateTotal()
    }
  } catch (error) {
    console.error('获取购物车列表失败:', error)
    ElMessage.error('获取购物车列表失败')
  }
}

// 提交订单
const submitOrder = async () => {
  try {
    // 构造订单商品数据
    const skuList = cartItems.value.map((item) => ({
      skuId: item.productSku.skuId,
      qty: item.cart.qty
    }))

    // 调用下单接口
    const params = {
      skuList: skuList,
      remark: remark.value
    }

    const res = await placeOrder(params)
    if (res) {
      ElMessage.success('订单提交成功')
      // 跳转到订单详情或其他页面
      router.push({
        name: 'UserOrderDetail',
        query: { orderNo: res.data.orderNo }
      })
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败')
  }
}

// 初始化
onMounted(() => {
  fetchCartList()
})

// 格式化规格显示
const formatSpecs = (attrValueList: { pnValue: string; pvValue: string }[] | undefined) => {
  if (!attrValueList || attrValueList.length === 0) {
    return '无属性信息'
  }
  return attrValueList.map((attr) => `${attr.pnValue}:${attr.pvValue}`).join('，')
}
</script>

<template>
  <HomeWrap>
    <div class="main-wrap">
      <h2 class="page-title">订单确认</h2>
      <div class="goods-list">
        <div v-for="item in cartItems" :key="item.cart.cartId" class="goods-item">
          <el-image
            :src="item.productSku.mainImg || '/images/1.webp'"
            class="goods-img"
            fit="cover"
          />
          <div class="goods-info">
            <div class="goods-title">{{ item.productSku.title }}</div>
            <div class="goods-specs">{{ formatSpecs(item.productSku.attrValueList) }}</div>
            <div class="goods-price-qty">
              <span class="price">¥{{ item.productSku.price }}</span>
              <span class="qty">x {{ item.cart.qty }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="remark-section">
        <el-input
          v-model="remark"
          type="textarea"
          placeholder="请输入订单备注（可选）"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </div>
    </div>

    <!-- 结算吸底栏 -->
    <div class="checkout-bar">
      <div class="total">
        合计：<span class="money">￥{{ totalMoney.toFixed(2) }}</span>
      </div>
      <el-button type="primary" size="large" round @click="submitOrder">提交订单</el-button>
    </div>
  </HomeWrap>
</template>

<style scoped>
.page-title {
  padding: 16px;
}
.goods-list {
  padding: 16px;
}

.goods-item {
  display: flex;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.goods-img {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  margin-right: 12px;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.goods-specs {
  font-size: 14px;
  color: #999;
  margin-bottom: 8px;
}

.goods-price-qty {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.qty {
  font-size: 14px;
  color: #666;
}

.remark-section {
  padding: 0 16px 16px;
}

.checkout-bar {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.total {
  font-size: 16px;
}

.total .money {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

/* 给主体留 56px 安全区，防止内容被遮挡 */
.main-wrap {
  padding-bottom: 50px;
}
</style>
